package cn.turing.firecontrol.device.util;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Random;

/**
 * @Author: 赵贤
 */
public class TencentCOSUtil {
//    SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理


    public static String secretId =  "AKIDhEdomY6PlwvfEajdJkz1oeGfqqdCYgaG";


    public static String secretKey = "WorfEdy73mOnywjJhsskdJm273oMhpnb";

    //储存捅地区
    public static String region = "ap-beijing";

    //储存桶名字

    public static String bucketName = "ikun-1316668478";

    //文件上传地址

    public static String url = "https://ikun-1316668478.cos.ap-beijing.myqcloud.com/";

    public static COSCredentials credentials = new BasicCOSCredentials(secretId, secretKey);
    // 配置 COS 区域 就购买时选择的区域 我这里是 广州（guangzhou）
    public static ClientConfig clientConfig = new ClientConfig(new Region(region));

    //腾讯云cos小文件上传
    public static String uploadfile(MultipartFile file){
    	// 创建 COS 客户端连接
        COSClient cosClient = new COSClient(credentials,clientConfig);
        String fileName = file.getOriginalFilename();
        try {
            String substring = fileName.substring(fileName.lastIndexOf("."));
            File localFile = File.createTempFile(String.valueOf(System.currentTimeMillis()),substring);
            file.transferTo(localFile);
            Random random = new Random();
            fileName =random.nextInt(10000)+System.currentTimeMillis()+substring;
            // 将 文件上传至 COS 
            PutObjectRequest objectRequest = new PutObjectRequest(bucketName,fileName,localFile);
            cosClient.putObject(objectRequest);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            cosClient.shutdown();
        }
        return url+fileName;
    }
}